<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="销售退货单号" prop="returnNo">
        <el-input
          v-model="queryParams.returnNo"
          placeholder="请输入销售退货单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户编号" prop="customerId">
        <el-input
          v-model="queryParams.customerId"
          placeholder="请输入客户编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结算账户编号" prop="accountId">
        <el-input
          v-model="queryParams.accountId"
          placeholder="请输入结算账户编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售员编号" prop="saleUserId">
        <el-input
          v-model="queryParams.saleUserId"
          placeholder="请输入销售员编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="退货时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeReturnTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="销售订单 id" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入销售订单 id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入销售订单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合计数量" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入合计数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否删除" prop="deleted">
        <el-input
          v-model="queryParams.deleted"
          placeholder="请输入是否删除"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['sale:return:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sale:return:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sale:return:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['sale:return:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="returnList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="销售退货单号" align="center" prop="returnNo" />
      <el-table-column label="退货状态" align="center" prop="status" />
      <el-table-column label="客户编号" align="center" prop="customerId" />
      <el-table-column label="结算账户编号" align="center" prop="accountId" />
      <el-table-column label="销售员编号" align="center" prop="saleUserId" />
      <el-table-column label="退货时间" align="center" prop="returnTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售订单 id" align="center" prop="orderId" />
      <el-table-column label="销售订单号" align="center" prop="orderNo" />
      <el-table-column label="合计数量" align="center" prop="number" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="是否删除" align="center" prop="deleted" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['sale:return:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['sale:return:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销售退货对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="returnRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="销售退货单号" prop="returnNo">
          <el-input v-model="form.returnNo" placeholder="请输入销售退货单号" />
        </el-form-item>
        <el-form-item label="客户编号" prop="customerId">
          <el-input v-model="form.customerId" placeholder="请输入客户编号" />
        </el-form-item>
        <el-form-item label="结算账户编号" prop="accountId">
          <el-input v-model="form.accountId" placeholder="请输入结算账户编号" />
        </el-form-item>
        <el-form-item label="销售员编号" prop="saleUserId">
          <el-input v-model="form.saleUserId" placeholder="请输入销售员编号" />
        </el-form-item>
        <el-form-item label="退货时间" prop="returnTime">
          <el-date-picker clearable
            v-model="form.returnTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择退货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="销售订单 id" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入销售订单 id" />
        </el-form-item>
        <el-form-item label="销售订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入销售订单号" />
        </el-form-item>
        <el-form-item label="合计数量" prop="number">
          <el-input v-model="form.number" placeholder="请输入合计数量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="是否删除" prop="deleted">
          <el-input v-model="form.deleted" placeholder="请输入是否删除" />
        </el-form-item>
        <el-divider content-position="center">销售退货产品信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddSaleReturnProduct">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteSaleReturnProduct">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="saleReturnProductList" :row-class-name="rowSaleReturnProductIndex" @selection-change="handleSaleReturnProductSelectionChange" ref="saleReturnProduct">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="仓库编号" prop="warehouseId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.warehouseId" placeholder="请输入仓库编号" />
            </template>
          </el-table-column>
          <el-table-column label="产品编号" prop="productId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.productId" placeholder="请输入产品编号" />
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="count" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.count" placeholder="请输入数量" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Return">
import { listReturn, getReturn, delReturn, addReturn, updateReturn } from "@/api/sale/return";

const { proxy } = getCurrentInstance();

const returnList = ref([]);
const saleReturnProductList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedSaleReturnProduct = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeReturnTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    returnNo: null,
    status: null,
    customerId: null,
    accountId: null,
    saleUserId: null,
    returnTime: null,
    orderId: null,
    orderNo: null,
    number: null,
    deleted: null
  },
  rules: {
    returnNo: [
      { required: true, message: "销售退货单号不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "退货状态不能为空", trigger: "change" }
    ],
    customerId: [
      { required: true, message: "客户编号不能为空", trigger: "blur" }
    ],
    accountId: [
      { required: true, message: "结算账户编号不能为空", trigger: "blur" }
    ],
    saleUserId: [
      { required: true, message: "销售员编号不能为空", trigger: "blur" }
    ],
    returnTime: [
      { required: true, message: "退货时间不能为空", trigger: "blur" }
    ],
    orderId: [
      { required: true, message: "销售订单 id不能为空", trigger: "blur" }
    ],
    orderNo: [
      { required: true, message: "销售订单号不能为空", trigger: "blur" }
    ],
    number: [
      { required: true, message: "合计数量不能为空", trigger: "blur" }
    ],
    createBy: [
      { required: true, message: "创建者不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询销售退货列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeReturnTime && '' != daterangeReturnTime) {
    queryParams.value.params["beginReturnTime"] = daterangeReturnTime.value[0];
    queryParams.value.params["endReturnTime"] = daterangeReturnTime.value[1];
  }
  listReturn(queryParams.value).then(response => {
    returnList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    returnNo: null,
    status: null,
    customerId: null,
    accountId: null,
    saleUserId: null,
    returnTime: null,
    orderId: null,
    orderNo: null,
    number: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleted: null
  };
  saleReturnProductList.value = [];
  proxy.resetForm("returnRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeReturnTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加销售退货";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getReturn(_id).then(response => {
    form.value = response.data;
    saleReturnProductList.value = response.data.saleReturnProductList;
    open.value = true;
    title.value = "修改销售退货";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["returnRef"].validate(valid => {
    if (valid) {
      form.value.saleReturnProductList = saleReturnProductList.value;
      if (form.value.id != null) {
        updateReturn(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addReturn(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除销售退货编号为"' + _ids + '"的数据项？').then(function() {
    return delReturn(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 销售退货产品序号 */
function rowSaleReturnProductIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 销售退货产品添加按钮操作 */
function handleAddSaleReturnProduct() {
  let obj = {};
  obj.warehouseId = "";
  obj.productId = "";
  obj.count = "";
  obj.remark = "";
  saleReturnProductList.value.push(obj);
}

/** 销售退货产品删除按钮操作 */
function handleDeleteSaleReturnProduct() {
  if (checkedSaleReturnProduct.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的销售退货产品数据");
  } else {
    const saleReturnProducts = saleReturnProductList.value;
    const checkedSaleReturnProducts = checkedSaleReturnProduct.value;
    saleReturnProductList.value = saleReturnProducts.filter(function(item) {
      return checkedSaleReturnProducts.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleSaleReturnProductSelectionChange(selection) {
  checkedSaleReturnProduct.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sale/return/export', {
    ...queryParams.value
  }, `return_${new Date().getTime()}.xlsx`)
}

getList();
</script>
